package icu.wangrui.bookstore.controller;

import icu.wangrui.bookstore.dto.BookDTO;
import icu.wangrui.bookstore.pojo.Book;
import icu.wangrui.bookstore.pojo.User;
import icu.wangrui.bookstore.service.impl.BookServiceImpl;
import icu.wangrui.bookstore.service.impl.UserServiceImpl;
import icu.wangrui.bookstore.utils.SendEmail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
@RequestMapping("/user/page")
public class UserIndexController {
    @Autowired
    private BookServiceImpl bookService;
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private SendEmail sendEmail;

/*    @RequestMapping("/index")
    public String indexSearchController(){
        return "/user/page/test-index";
    }*/

    @GetMapping("/index")
    public String indexController(Model model,
                                  @RequestParam(name = "page",defaultValue = "1") Integer page){
        List<BookDTO> bookDTOList = bookService.showAllBook(page);
        //BookDTO里是两个对象
        for (BookDTO bookDTO : bookDTOList) {
            List<Book> books = bookDTO.getBooks();
            model.addAttribute("books",books);
            model.addAttribute("bookPageInfo",bookDTO.getBookPageInfo());
        }
        return "/user/page/index";
    }

        @GetMapping("/search")
        public String parse(@RequestParam(name="keyword") String keyword,
                            Model model) throws Exception {
            List<Map<String, Object>> bookESList = bookService.searchPageHighlightBuilder(keyword, 0, 4);
            List<Book> books = new ArrayList<>();
            for (Map<String, Object> stringObjectMap : bookESList) {
                Book book = new Book();
               book.setTitle((String) stringObjectMap.get("title"));
                book.setIsbn((String) stringObjectMap.get("isbn"));
                book.setAuthor((String) stringObjectMap.get("author"));
                book.setPress((String) stringObjectMap.get("press"));
                book.setPrice((Double) stringObjectMap.get("price"));
                books.add(book);
            }
            model.addAttribute("books",books);
            return "/user/page/test-index";
        }

    @GetMapping("/detail")
    public String detail(Model model,
                         HttpServletRequest request,
                         @RequestParam(name = "isbn") String isbn){
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("loginUser");
        if(user!=null) {
            String phone = user.getPhone();
            boolean b = bookService.selectCollectByPhoneAndIsbn(phone, isbn);
            model.addAttribute("b",b);
        }
        Book book = bookService.showBookByIsbn(isbn);
        model.addAttribute("book",book);
        return "/user/page/detail";
    }

    @GetMapping("/collect")
    public String collect(Model model, HttpServletRequest request){
        User loginUser = (User)request.getSession().getAttribute("loginUser");
        if(loginUser==null) {
            return "redirect:/userlogin.html";
        }else{
            List<Book> books = bookService.showBookByUser(loginUser);
            model.addAttribute("books",books);
            return "/user/page/collect";
        }
    }
    /**
     * @Author 王锐
     * @Date 2020/5/7 0007 10:23
     * @Description 根据状态判断 删除还是添加
     * @Param [model, request, isbn, phone, status]
     * @Return java.lang.Boolean
     * @Since version-1.0
     */
    @RequestMapping("/addOrDelCollect")
    @ResponseBody
    public String addOrDelCollect(Model model,
                                  HttpServletRequest request,
                                  @RequestParam(name = "isbn") String isbn){
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("loginUser");
        String phone="";
        String msg="";
        if(user!=null) {
            phone = user.getPhone();
            boolean b = bookService.selectCollectByPhoneAndIsbn(phone, isbn);
            if (b){
                bookService.delCollectByPhoneAndIsbn(phone, isbn);
                msg="no";

            }else{
                bookService.insertCollectByPhoneAndIsbn(phone, isbn);
                msg="yes";
            }
        }
        return msg;

    }
    @RequestMapping("/emailCheck")
    @ResponseBody
    public String emailCheck(HttpSession httpSession,
                             @RequestParam(name = "email") String email) throws MessagingException {
        User user = userService.checkUserByEmail(email);
        if (user == null) {
            return null;
        }else {
            String code = sendEmail.getCode();
            httpSession.setAttribute("code",code);
            httpSession.setAttribute("emailUser",user);
            httpSession.setMaxInactiveInterval(60);//An integer specifying the number of seconds单位为秒
            String subject = "学子商城密码修改验证";
            String text = "你的验证码为：<p style='color:red'>"+code+"</p>,1分钟内有效。打死也不要告诉别人！";
            sendEmail.sendMail(false,subject,text,email);
            return "ok";
        }
    }

    @RequestMapping("/codeCheck")
    @ResponseBody
    public String codeCheck(HttpServletRequest request,
                             @RequestParam(name = "code") String code){
            HttpSession session = request.getSession();
            String oldCode = (String)session.getAttribute("code");
            if (code == null) {
                return null;
            }
            if (oldCode.isEmpty()){
                return "timeOut";
            }else if(code.equals(oldCode)){
                return "ok";
            }else {
                return "no";
            }
        }
        @RequestMapping("/changePassword")
        @ResponseBody
        public String changePassword(HttpSession httpSession,
                             @RequestParam(name = "cpwd") String cpwd) throws MessagingException {
            User emailUser = (User)httpSession.getAttribute("emailUser");
            if (emailUser != null) {
                Boolean aBoolean = userService.updateUserPasswordbyPhone(emailUser.getPhone(), cpwd);
                if (aBoolean){
                    String subject = "学子商城修改信息后的信息";
                    String text = "你修改后的信息：<h3 style='color:red'>用户名："+emailUser.getUname()+"-----新密码："+cpwd+"</h3>";
                    sendEmail.sendMail(false,subject,text,emailUser.getEmail());
                    return "ok";
                }
                return "no";
            }else {
                return "no";
            }

        }
}
